<template>
  <div class="card mb-4">
    <div class="card-body">
      <h5 class="card-title">{{ isEditing ? '编辑任务' : '创建新任务' }}</h5>
      <form @submit.prevent="submitTask">
        <div class="mb-3">
          <label for="title" class="form-label">任务标题</label>
          <input v-model="task.title" type="text" class="form-control" id="title" required />
        </div>
        <div class="mb-3">
          <label for="description" class="form-label">描述</label>
          <textarea v-model="task.description" class="form-control" id="description"></textarea>
        </div>
        <div class="mb-3">
          <label for="status" class="form-label">状态</label>
          <select v-model="task.status" class="form-select">
            <option value="pending">待处理</option>
            <option value="in_progress">进行中</option>
            <option value="completed">已完成</option>
            <option value="on_hold">暂停</option>
            <option value="cancelled">已取消</option>
          </select>
        </div>
        <button type="submit" class="btn btn-primary">{{ isEditing ? '保存' : '提交' }}</button>
        <button v-if="isEditing" type="button" class="btn btn-secondary ms-2" @click="cancelEdit">
          取消
        </button>
      </form>
    </div>
  </div>
</template>

<script>
import { createTask, updateTask } from '../api';

export default {
  name: 'TaskForm',
  props: {
    taskToEdit: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      task: {
        title: '',
        description: '',
        status: 'pending',
      },
      isEditing: false,
    };
  },
  watch: {
    taskToEdit: {
      immediate: true,
      handler(newTask) {
        if (newTask) {
          this.task = { ...newTask };
          this.isEditing = true;
        } else {
          this.resetForm();
        }
      },
    },
  },
  methods: {
    async submitTask() {
      try {
        if (this.isEditing) {
          await updateTask(this.task.id, {
            title: this.task.title,
            description: this.task.description,
            status: this.task.status,
          });
          this.$emit('task-updated');
        } else {
          await createTask(this.task);
          this.$emit('task-created');
        }
        this.resetForm();
      } catch (error) {
        console.error(`${this.isEditing ? '更新' : '创建'}任务失败:`, error);
      }
    },
    resetForm() {
      this.task = { title: '', description: '', status: 'pending' };
      this.isEditing = false;
      this.$emit('cancel-edit');
    },
    cancelEdit() {
      this.resetForm();
    },
  },
};
</script>